<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 闪银付
 */
class ShanyinfuController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        $data = array();
		
        $data['order_no'] = $return['orderid'];
        $data['amount'] = $return['amount'];
        $data['order_desc'] = 'zf';
        $data['notify_url'] = $return['notifyurl'];
        switch($this->config['paytype']) {
            //微信
            case 1:
                $data['order_type'] = '1';
                break;
            //支付宝
            case 3:
                $data['order_type'] = '0';
                break;
            //支付宝H5
            case 4:
                $data['order_type'] = '0';
                break;
            default:
                $this->showmessage('暂不支持此支付方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
		
		$current = $this->getMillisecondTimeStamp();
		$nonce = mt_rand(100000,999999);
		//$appKey = $this->config['signkey'];//你们的商户签名
		//$appsecret = $this->config['appsecret'];//你们的商户秘钥
		
		$str = "sign=" . $nonce . $current . $this->config['signkey'] . $this->config['appsecret'];
		$authorization = md5($str);
		
		//echo "请求地址：" . $this->config['gateway'] . "<br/><br/>";
		//echo "签名字符串：" . $str . '<br/><br/>';
		
		$headerArr = array(
			"Nonce" => $nonce,
			"Cur" => $current,
			"Appkey" => $this->config['signkey'],
			"Authorization" => $authorization
		);
		
		$res = $this->http_curl($this->config['gateway'], json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $headerArr);
		$res = json_decode($res, true);
		
		$code = $res['data']['pay_url'];

        if(!$code){
            if($res['message']){
                $this->showmessage($res['message'],['code'=>C("THIRDCODES.".$this->class)]);
            }

            $this->showmessage('获取二维码失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }
		

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        //$this->assign("code_url", $res['data']['payurl']);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //微信
            case 1:
                $this->display("WeiXin/weixin");
                break;
            //支付宝扫码
            case 3:
                //支付宝H5
            case 4:
                if(isMobile()){
					header("Location:{$code}"); exit;
                    $this->display("WeiXin/alipaywap");
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            //支付宝
            case 17:
                $this->display("WeiXin/alipay");
                break;
            //支付宝H5
            case 18:
                $this->display("WeiXin/alipay");
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }
	
	private function getMillisecondTimeStamp() {
		list($usec, $sec) = explode(" ", microtime());
		return $sec .  round($usec * 1000);
	}
	
	private function http_curl($url, $data = '',$header = '') {
		//echo '<pre/>'; print_r($data); echo '<br/>'; print_r($header);
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		//设置请求头
		$header = array(
			"Accept: application/json",
			"Content-Type: application/json;charset=utf-8",
			"Authorization:".$header['Authorization'],
			"Nonce:".$header['Nonce'],
			"Cur:".$header['Cur'],
			"Appkey:".$header['Appkey']
		);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$file_contents = curl_exec($ch);
		curl_close($ch);
		return $file_contents;
	}

    //通知
    public function notifyurl(){
		$p = $origin = file_get_contents("php://input");
		
        //$p = $origin = '{"order_no":"2019012419000996981","amount":"10","create_time":1548327609192,"user_id":"038aa0a1f477771d778e4df606c24466","sign":"f470fa27a821396fd88db8d827bca410","order_id":"d375c5a7-7c60-4e1a-8d20-5c93bc304b2b"}';
		
        $p = json_decode($p, true);
		
        if(!$p || empty($p)){
            exit("wrong");
        }
		
		/*
		Array
		(
			[order_no] => 2019012419000996981
			[amount] => 10
			[create_time] => 1548327609192
			[user_id] => 038aa0a1f477771d778e4df606c24466
			[sign] => f470fa27a821396fd88db8d827bca410
			[order_id] => d375c5a7-7c60-4e1a-8d20-5c93bc304b2b
		)*/

        //获取订单信息
        $orderid = $p['order_no'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
      /*  M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            //"pay_orderid_rd"=>$p['sysnumber']
        ));*/

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $sign = $p['sign'];
        unset($p['sign']);

        ksort($p);

        $str = httpstr($p) . $this->config['appsecret'];
        $sign2 = md5($str);

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        $this->async($find['pay_orderid'], 'success');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}